package cn.com.libertymutual.sp.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

import cn.com.libertymutual.core.email.IEmailService;
import cn.com.libertymutual.core.util.DateUtil;
import cn.com.libertymutual.core.util.InsureUtils;
import cn.com.libertymutual.core.util.StringUtil;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.bean.TbSpCheckCode;
import cn.com.libertymutual.sp.dao.CheckCodeDao;
import cn.com.libertymutual.sp.service.api.QueryPrdCodeService;
import cn.com.libertymutual.wx.common.ResponseMessageParser;
import cn.com.libertymutual.wx.message.responsedto.TextMessage;

@Service("queryPrdCodeService")
public class QueryPrdCodeServiceImpl implements QueryPrdCodeService {
	private Logger log = LoggerFactory.getLogger(getClass());
	@Resource
	private CheckCodeDao checkCodeDao;
	@Autowired
	private JdbcTemplate readJdbcTemplate;
	@Resource
	private IEmailService emailService;

	@Value("${checkCode.emails}")
	private String emails;

	@Override
	public ServiceResult queryCheckCode() {
		ServiceResult sr = new ServiceResult();
		sr.setFail();
		String code = "";
		String checkDate = DateUtil.dateFromat(new Date(), DateUtil.DATE_TIME_PATTERN3);
		try {
			List<TbSpCheckCode> list = checkCodeDao.findByCheckDate(checkDate);
			if (null == list || list.size() == 0) {
				code = InsureUtils.checkCode(6);
				TbSpCheckCode checkCode = new TbSpCheckCode(code, checkDate, "1", new Date());
				checkCodeDao.save(checkCode);
				String info = checkDate + "的验车码为：" + code;
				log.info(info);
				// 邮件发送
				if (StringUtil.isNotEmpty(emails)) {
					List<Map<String, Object>> oneMothList = readJdbcTemplate.queryForList(
							"SELECT CHECK_DATE as checkDate,CODE as code from tb_sp_checkcode where status='1' and DATE_SUB(CURDATE(), INTERVAL 1 MONTH) <= STR_TO_DATE(CHECK_DATE,'%Y%m%d') order by create_Time desc");
					StringBuilder htmls = new StringBuilder("日   期&nbsp &nbsp验证码<br>");
					for (Map<String, Object> spCheckCode : oneMothList) {
						htmls.append(spCheckCode.get("checkDate")).append("&nbsp &nbsp").append(spCheckCode.get("code")).append("<br>");
					}
					List<String> toEmils = Arrays.asList(emails.split(","));
					emailService.sendEmail("验车码", htmls.toString(), toEmils, Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList(), true);
					log.info(htmls.toString() + "验车码发送至：" + emails.split(","));
				}
			} else {
				// 每日0点到24点保持唯一编码不变
				code = list.get(0).getCode();
			}
			sr.setSuccess();
			sr.setResult(DateUtil.dateFromat(new Date(), DateUtil.PATTERN_M_D_CH) + "验车码为：" + code);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		log.info(checkDate + "的验车码为：" + code);

		// 生成第二天的验车码
		/*
		 * try { String checkDate2=DateUtil.dateFromat(DateUtil.tomorrow(new Date()),
		 * DateUtil.DATE_TIME_PATTERN3); List<TbSpCheckCode>
		 * list=checkCodeDao.findByCheckDate(checkDate2); if(null==list ||
		 * list.size()==0){ String code2=InsureUtils.checkCode(6); TbSpCheckCode
		 * checkCode=new TbSpCheckCode(code2,checkDate2,"1",new Date());
		 * checkCodeDao.save(checkCode); String info=checkDate2+"的验车码为："+code2;
		 * log.info(info); //邮件发送 if(StringUtil.isNotEmpty(emails)){
		 * List<Map<String,Object>> oneMothList=readJdbcTemplate.
		 * queryForList("SELECT CHECK_DATE as checkDate,CODE as code from tb_sp_checkcode where status='1' and DATE_SUB(CURDATE(), INTERVAL 1 MONTH) <= STR_TO_DATE(CHECK_DATE,'%Y%m%d') order by create_Time desc"
		 * ); StringBuilder htmls=new StringBuilder("日   期&nbsp &nbsp验证码<br>");
		 * for(Map<String,Object> spCheckCode:oneMothList){
		 * htmls.append(spCheckCode.get("checkDate")).append("&nbsp &nbsp").append(
		 * spCheckCode.get("code")).append("<br>"); } List<String>
		 * toEmils=Arrays.asList(emails.split(",")); emailService.sendEmail("验车码",
		 * htmls.toString(),
		 * toEmils,Lists.newArrayList(),Lists.newArrayList(),Lists.newArrayList(),true);
		 * log.info(htmls.toString()+"验车码发送至："+emails.split(",")); } } } catch
		 * (Exception e) { log.error(e.getMessage(), e); }
		 */
		return sr;
	}

	@Override
	public String executeQueryCheckCode(String returnXML, TextMessage textMessage) {
		ServiceResult sr = this.queryCheckCode();
		if (sr.getState() == ServiceResult.STATE_SUCCESS) {
			// 回复6位验车码
			textMessage.setContent(sr.getResult().toString());
		} else {
			// 回复提醒信息
			textMessage.setContent("请输入\"验车码\"关键词");
		}
		returnXML = ResponseMessageParser.textMessageToXml(textMessage);
		log.info("验车码回复内容：{}", returnXML);
		return returnXML;
	}

}
